package com.cxg.fairy.ui.widget.CountTimer;

import android.content.Context;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatTextView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;

/**
 * Created by Administrator on 2018/4/26.
 */

public class CountTimer extends CountDownTimer {

    private SpannableStringBuilder sb;
    private ForegroundColorSpan colorSpan;
    private Context mContext;
    private AppCompatTextView mTvCaptcha;

    /**
     * @param millisInFuture    The number of millis in the future from the call
     *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
     *                          is called.
     * @param countDownInterval The interval along the way to receive
     *                          {@link #onTick(long)} callbacks.
     */
    public CountTimer(long millisInFuture, long countDownInterval,Context context,AppCompatTextView tvCaptcha) {
        super(millisInFuture, countDownInterval);
        this.mContext = context;
        this.mTvCaptcha = tvCaptcha;
        sb = new SpannableStringBuilder();
        colorSpan = new ForegroundColorSpan(ContextCompat.getColor(context, android.R.color.holo_blue_dark));
    }

    /**
     * 倒计时过程中调用
     * @param millisUntilFinished
     */
    @Override
    public void onTick(long millisUntilFinished) {
        Log.e("Tag", "millisUntilFinished=" + millisUntilFinished);
//            Log.e("Tag", "倒计时=" + (millisUntilFinished/1000));
        //处理后的倒计时数值
        int time = (int) (Math.round((double) millisUntilFinished / 1000) - 1);
        //拼接要显示的字符串
        sb.clear(); //先把之前的字符串清除
        Log.e("Tag", "字符长度=" + sb.length());
        sb.append(String.valueOf(time));
        sb.append("s后重新发送");
        int index = String.valueOf(sb).indexOf("后");
        //给秒数和单位设置蓝色前景色
        sb.setSpan(colorSpan, 0, index, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        mTvCaptcha.setText(sb);
        //设置倒计时中的按钮外观
        mTvCaptcha.setClickable(false);//倒计时过程中将按钮设置为不可点击
        mTvCaptcha.setBackgroundColor(Color.parseColor("#c7c7c7"));
        mTvCaptcha.setTextColor(ContextCompat.getColor(mContext, android.R.color.black));
        mTvCaptcha.setTextSize(10);
    }

    /**
     * 倒计时完成后调用
     */
    @Override
    public void onFinish() {
        Log.e("Tag", "倒计时完成");
        //设置倒计时结束之后的按钮样式
        mTvCaptcha.setBackgroundColor(ContextCompat.getColor(mContext, android.R.color.holo_blue_light));
        mTvCaptcha.setTextColor(ContextCompat.getColor(mContext, android.R.color.white));
        mTvCaptcha.setTextSize(12);
        mTvCaptcha.setText("重新发送");
        mTvCaptcha.setClickable(true);
    }
}
